package com.atguigu.dwm.model.service.impl;

import com.atguigu.dwm.common.bean.QueryInfo;
import com.atguigu.dwm.common.bean.Result;
import com.atguigu.dwm.common.component.TableHiveProcessor;
import com.atguigu.dwm.common.constants.CommonCodes;
import com.atguigu.dwm.common.util.SqlUtil;
import com.atguigu.dwm.model.bean.DmDimension;
import com.atguigu.dwm.model.bean.DmTable;
import com.atguigu.dwm.model.bean.DmTableColumn;
import com.atguigu.dwm.model.mapper.DmTableMapper;
import com.atguigu.dwm.model.service.DmTableColumnService;
import com.atguigu.dwm.model.service.DmTableService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据表 服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2024-07-03
 */
@Service
@DS("dwm")
public class DmTableServiceImpl extends ServiceImpl<DmTableMapper, DmTable> implements DmTableService {

    @Autowired
    DmTableColumnService dmTableColumnService;



    @Transactional
    public  void  saveTableAll(DmTable dmTable){
        dmTable.setLastUpdateTime(new Date());
        dmTable.setLastUpdateUserId(9999L);
        this.saveOrUpdate(dmTable);//保存后 会把主键补充在id上
        int seq=1;
        if(dmTable.getTableColumns()!=null){
            for (DmTableColumn tableColumn : dmTable.getTableColumns()) {
                tableColumn.setTableId(dmTable.getId());
                tableColumn.setSeq(seq++);
                tableColumn.setIsPartitionCol("0");
                tableColumn.setLastUpdateTime(new Date());
                tableColumn.setLastUpdateUserId(9999L);
            }
        }
        seq=1;
        if(dmTable.getPartitionColumns()!=null){
            for (DmTableColumn partitionColumn : dmTable.getPartitionColumns()) {
                partitionColumn.setTableId(dmTable.getId());
                partitionColumn.setSeq(seq++);
                partitionColumn.setIsPartitionCol("1");
                partitionColumn.setLastUpdateTime(new Date());
                partitionColumn.setLastUpdateUserId(9999L);
            }
        }
        dmTableColumnService.saveOrUpdateBatch(dmTable.getTableColumns());
        dmTableColumnService.saveOrUpdateBatch(dmTable.getPartitionColumns());


        //清理掉已经删除的列
        List<Long> colsIdList = dmTable.getTableColumns().stream().map(dmTableColumn -> dmTableColumn.getId()).collect(Collectors.toList());
        if(dmTable.getPartitionColumns()!=null){
            List<Long> partColsIdList = dmTable.getPartitionColumns().stream().map(dmTableColumn -> dmTableColumn.getId()).collect(Collectors.toList());
            colsIdList.addAll(partColsIdList);
        }
       UpdateWrapper<DmTableColumn> updateWrapper = new UpdateWrapper<DmTableColumn>().set("is_deleted", "1")
                .eq("table_id", dmTable.getId())
                .notIn("id", colsIdList);
        dmTableColumnService.update(updateWrapper);

    }

    @Override
    public List<DmTable> getQueryList(QueryInfo queryInfo) {
        String condition = "";
        if(queryInfo.getModelId()!=null){
            condition=" and  t.model_id="+queryInfo.getModelId();
        }
        if(queryInfo.getTableNameQuery()!=null&&queryInfo.getTableNameQuery().trim().length()>0){
            condition+=" and ( t.table_name like '%"+ SqlUtil.filterUnsafeSql( queryInfo.getTableNameQuery())+"%' " +
                    "or  t.table_name_chn like '%"+SqlUtil.filterUnsafeSql( queryInfo.getTableNameQuery())+"%' ) ";

        }
        condition+= queryInfo.getLimitSql();


        List<DmTable> list  = this.baseMapper.selectQueryList(condition);
        return list;
    }


    public Integer getQueryTotal(QueryInfo queryInfo) {
        String condition = "";
        if(queryInfo.getModelId()!=null){
            condition=" and  t.model_id="+queryInfo.getModelId();
        }
        if(queryInfo.getTableNameQuery()!=null&&queryInfo.getTableNameQuery().trim().length()>0){
            condition+=" and ( t.table_name like '%"+ SqlUtil.filterUnsafeSql( queryInfo.getTableNameQuery())+"%' " +
                    "or  t.table_name_chn like '%"+SqlUtil.filterUnsafeSql( queryInfo.getTableNameQuery())+"%' ) ";

        }
        Integer total = this.baseMapper.selectQueryCount(condition);
        return total;
    }

    @Override
    public DmTable getTableAll(Long id) {
        DmTable dmTable = this.getById(id);

        List<DmTableColumn> tableColumns = dmTableColumnService.list(new QueryWrapper<DmTableColumn>()
                .eq("is_deleted", "0")
                .eq("table_id", id)
                .eq("is_partition_col", "0")
                .orderByAsc("seq"));
        dmTable.setTableColumns(tableColumns);

        List<DmTableColumn> pTableColumns = dmTableColumnService.list(new QueryWrapper<DmTableColumn>()
                .eq("is_deleted", "0")
                .eq("table_id", id)
                .eq("is_partition_col", "1")
                .orderByAsc("seq"));
        dmTable.setPartitionColumns(pTableColumns);

        return dmTable;
    }

    @Autowired
    TableHiveProcessor tableHiveProcessor;

    // 1 根据id查询DmTable 包含字段
    // 2 根据DmTable ->调用hiveProcessor建表
    // 3  修改状态
    @Override
    public void submitToHive(Long tableId) throws  Exception {
        // 1 根据id查询DmTable 包含字段
        DmTable dmTable = this.getTableAll(tableId);
        // 2 根据DmTable ->调用hiveProcessor建表
        tableHiveProcessor.createTable(dmTable);
        // 3  修改状态
        dmTable.setTableStatus(CommonCodes.TABLE_STATUS_PUBLISHED);
        dmTable.setLastUpdateTime(new Date());
        dmTable.setLastUpdateUserId(9999L);

        this.saveOrUpdate(dmTable);
    }
}

// ' or 1=1 or '1' like '
